$(function(){





    $("#user-comments").html(usercomment);
    //刚加载就发起请求，刷新评论，并定义各个方法
    var showtext=[];
    var sourse=[];
    var $model=$("#voicemodel").clone(true).removeClass("hidden").addClass("users-voice").removeAttr("id");
    que_info.num=2;
    $.ajax({
        async : false,
        url:"?r=ajax/comment",
        data:que_info,
        dataType:'json',
        method:'get',
        success:function(data){
            var length=data.length;
            for(var i=0; i<length; i++){
                var $clone=$model.clone(true);
                sourse.push(data[i].comment_content)
                showtext.push(changeText(changeData(data[i].comment_content)));
                setHot(data[i],$clone);
                $clone.insertBefore(".add-more");
                $clone.hide();
                if (i<2) {
                    $clone.slideDown(500);
                }
            }
            //展开全文
            var $viewall=$(".view-all");
            var $comment=$(".user-comments");
            var flag=true;
            $comment.addClass("notshow");
            $viewall.click(function(){
                var index=$viewall.index(this);
                var $thiscomment=$(this).siblings(".user-comments");
                if ($thiscomment.hasClass("notshow")) {
                    $thiscomment.html(sourse[index]).removeClass("notshow");
                    $(this).text("点击收起全文");
                }else{
                    $thiscomment.html(showtext[index]).addClass("notshow");
                    $(this).text("点击展开全文");
                }
            });
            var $addmore=$(".add-more");
            $addmore.click(function(){
                var n=0;
                $(".users-voice").each(function(index,item){
                    var $this=$(this);
                    if (!$this.is(":visible")&&n<5) {
                        $this.slideDown(500);
                        n++;
                    }
                })
            });
            
            //点击图标播放
            var $audio=$(".hot-voice audio");
            $(".play-record").click(function(){
                var index=$(".play-record").index(this);
                if ($audio[index].paused) {    //已停止
                    $audio[index].play();
                    $audio.eq(index).siblings('img').attr("src","./images/xx.gif");
                    var tarid=data[index].user_id;
                    $.ajax({
                        url:'?r=ajax/view',
                        method:'post',
                        dataType:'json',
                        data:{
                            'tar':tarid,
                            'sou':current_userid,
                            'class2':que_info.class2,
                            'class1':que_info.class1,
                            'question':que_info.question,
                        }
                    })
                }else{                  //正在播放
                    $audio[index].currentTime=0;
                    $audio[index].pause();
                    $audio.eq(index).siblings('img').attr("src","./images/xx.jpg");
                }
            });
            setInterval(function(){
                $audio.each(function(){
                    if ($(this)[0].ended) {
                        $(this).siblings('img').attr("src","./images/xx.jpg");
                    }
                })
            },500)

            //点赞功能,只能点赞一次,点赞后添加一个hasClick的类
            $(".good-times>span").click(function(){
                var $this=$(this);

                //获取当前所在的下标index
                var $thisvoice=$this.closest(".good-times");
                var index=$(".good-times").index($thisvoice);
                var tarid=data[index].user_id;

                var $thisgood=$this.find(".goods");
                if (!$this.hasClass("isgood")) {
                    $thisgood.text(parseInt($thisgood.text())+1+'');
                    $this.addClass("isgood");
                    $.ajax({
                        url:'?r=ajax/like',
                        method:'post',
                        dataType:'json',
                        data:{
                            'tar':tarid,
                            'sou':current_userid,
                            'class2':que_info.class2,
                            'class1':que_info.class1,
                            'question':que_info.question,
                            'status':'like'
                        }
                    })
                }else{
                    $thisgood.text(parseInt($thisgood.text())-1+'');
                    $this.removeClass("isgood");
                    $.ajax({
                        url:'?r=ajax/like',
                        method:'post',
                        dataType:'json',
                        data:{
                            'tar':tarid,
                            'sou':current_userid,
                            'class2':que_info.class2,
                            'class1':que_info.class1,
                            'question':que_info.question,
                            'status':'unlike'
                        }
                    })
                }
            });
        }
    });


    // 点击分享调用ajax再次刷新评论
    var $share=$(".share");
    $share.click(function(){
        var comments=$("#user-comments").html();
        var que_info_comment=que_info;
        que_info_comment.comment=comments;
        $succeed.show();
        $.ajax({
            method:'post',
            url:'?r=ajax/comment',
            dataType:'json',
            data:que_info_comment,
            success:function(data){
                if (data.state) {
                    $(".users-voice").remove();
                    var showtext=[];
                    var sourse=[];
                    que_info.num=2;
                    $.ajax({
                        url:"?r=ajax/comment",
                        data:que_info,
                        dataType:'json',
                        method:'get',
                        success:function(data){
                            var length=data.length;
                            for(var i=0; i<length; i++){
                                var $clone=$model.clone(true);
                                sourse.push(data[i].comment_content)
                                showtext.push(changeText(changeData(data[i].comment_content)));
                                setHot(data[i],$clone);
                                $clone.insertBefore(".add-more");
                                $clone.hide();
                                if (i<2) {
                                    $clone.slideDown(500);
                                }
                            }
                            //展开全文
                            var $viewall=$(".view-all");
                            var $comment=$(".user-comments");
                            var flag=true;
                            $comment.addClass("notshow");
                            $viewall.click(function(){
                                var index=$viewall.index(this);
                                var $thiscomment=$(this).siblings(".user-comments");
                                if ($thiscomment.hasClass("notshow")) {
                                    $thiscomment.html(sourse[index]).removeClass("notshow");
                                    $(this).text("点击收起全文");
                                }else{
                                    $thiscomment.html(showtext[index]).addClass("notshow");
                                    $(this).text("点击展开全文");
                                }
                            })

                            var $addmore=$(".add-more");
                            $addmore.click(function(){
                                var n=0;
                                $(".users-voice").each(function(index,item){
                                    var $this=$(this);
                                    if (!$this.is(":visible")&&n<5) {
                                        $this.slideDown(500);
                                        n++;
                                    }
                                })
                            })

                            //点击图标播放
                            var $audio=$(".hot-voice audio");
                            $(".play-record").click(function(){
                                var index=$(".play-record").index(this);
                                if ($audio[index].paused) {    
                                    $audio[index].play();
                                    $audio.eq(index).siblings('img').attr("src","./images/xx.gif");
                                    var tarid=data[index].user_id;
                                    $.ajax({
                                        url:'?r=ajax/view',
                                        method:'post',
                                        dataType:'json',
                                        data:{
                                            'tar':tarid,
                                            'sou':current_userid,
                                            'class2':que_info.class2,
                                            'class1':que_info.class1,
                                            'question':que_info.question,
                                        }
                                    })
                                }else{                
                                    $audio[index].currentTime=0;
                                    $audio[index].pause();
                                    $audio.eq(index).siblings('img').attr("src","./images/xx.jpg");
                                }
                            });
                            setInterval(function(){
                                $audio.each(function(){
                                    if ($(this)[0].ended) {
                                        $(this).siblings('img').attr("src","./images/xx.jpg");
                                    }
                                })
                            },500)


                            //点赞功能,只能点赞一次,点赞后添加一个hasClick的类
                            $(".good-times>span").click(function(){
                                var $this=$(this);
                                //获取当前所在的下标index
                                var $thisvoice=$this.closest(".good-times");
                                var index=$(".good-times").index($thisvoice);
                                var tarid=data[index].user_id;

                                var $thisgood=$this.find(".goods");
                                if (!$this.hasClass("isgood")) {
                                    $thisgood.text(parseInt($thisgood.text())+1+'');
                                    $this.addClass("isgood");
                                    $.ajax({
                                        url:'?r=ajax/like',
                                        method:'post',
                                        dataType:'json',
                                        data:{
                                            'tar':tarid,
                                            'sou':current_userid,
                                            'class2':que_info.class2,
                                            'class1':que_info.class1,
                                            'question':que_info.question,
                                            'status':'like'
                                        }
                                    })
                                }else{
                                    $thisgood.text(parseInt($thisgood.text())-1+'');
                                    $this.removeClass("isgood");
                                    $.ajax({
                                        url:'?r=ajax/like',
                                        method:'post',
                                        dataType:'json',
                                        data:{
                                            'tar':tarid,
                                            'sou':current_userid,
                                            'class2':que_info.class2,
                                            'class1':que_info.class1,
                                            'question':que_info.question,
                                            'status':'unlike'
                                        }
                                    })
                                }
                            });
                        }
                    })
                }
            }
        })
    });

    //分享中的动画效果
    var $succeed=$("#comment-succeed");
    $succeed.hide();
    $(document).ajaxStop(function(){
        $succeed.hide();
    });


    $(".listen-wrap").hide();
    $(".text-article").click(function(){
        $(this).addClass("getNow");
        $(this).siblings().removeClass("getNow");
        $("#listen_wrap").hide();
        $("#text_wrap").show();
    });
    $(".text-info").click(function(){
        $(this).addClass("getNow");
        $(this).siblings().removeClass("getNow");
        $("#listen_wrap").show();
        $("#text_wrap").hide();
    })


});



//秒转化为分钟格式函数
function secToMinx(xsec){
	xsec=parseInt(xsec,10);
	var getstr=function(val){
		if (val<10) {return '0'+val}
		else return ''+val;
	};
	var min=parseInt(xsec/60);
	var sec=parseInt(xsec-min*60);
	return getstr(min)+":"+getstr(sec);
}
function changeText(val){
    if (val.length>120) {
        return val.slice(0,120)+'...';
    }else{
        return val;
    }
}
function changeData(val){
    val=val.replace(/\s{2,}|\<br\s*\/\>/g,' ')       //超过两个空字符或者是<br></br>都替换成空格
    return val;
}

function setHot(data,$demo){
    $demo.find(".play-record audio").attr("src",data.url);
    if (data.photo) {
        $demo.find(".user-pic img").attr("src",data.photo);
    }else{
        $demo.find(".user-pic img").attr("src","<?=Url::to('@web/images/default.jpg');?>");
    }
    $demo.find(".user-id").text(data.name);
    $demo.find(".user-date").text(data.comment_time);
    $demo.find(".views").text(data.play_num);
    $demo.find(".goods").text(data.like_num);
    $demo.find(".user-comments").html(changeText(changeData(data.comment_content)));
    var tx=$demo.find(".user-comments").text();
    var $cmts=$demo.find(".user-comments");
    var removetx='';
    if ($cmts.find(".selfText")) {
        removetx=$demo.find(".user-comments").find(".selfText").text();
    }
    tx=tx.replace(removetx,'');
    $demo.find(".user-comments").text(changeText(tx));
    var likepeo=data.like_ids;
    if (likepeo.indexOf(current_userid)!=-1&&likepeo.length>0) {
        $demo.find(".good-times>span").addClass("isgood");
    }
}

$(window).load(function(){

     //点击图标播放
    var $useaudio=$(".user-currecord audio");
    $(".user-currecord img").click(function(){
        if ($useaudio[0].paused) {    
            $useaudio[0].play();
            $(this).attr("src","./images/xx.gif");
        }else{                
            $useaudio[0].currentTime=0;
            $useaudio[0].pause();
            $(this).attr("src","./images/xx.jpg");
        }
    });
    setInterval(function(){
        if ($useaudio[0].ended) {
            $useaudio.siblings('img').attr("src","./images/xx.jpg");
        }
    },500)





    var $pauseplay=$(".player1 .pause-play");
    var audio=document.getElementById("audio1");
    var endsec=audio.duration;
    var isPlay=false;
    var $starttime=$(".player1 .start-time");
    var $endtime=$(".player1 .end-time");
    var $totalline=$(".player1 .play-line");
    var $curline=$(".player1 .play-current-line");
    var $playpoint=$(".player1 .play-point");
    var $faplay=$pauseplay.find('i');
    var $voltotalline=$(".player1 .volume-line");
    var volleft=$voltotalline.offset().left;
    var volwidth=$voltotalline.width();
    var $volpoint=$voltotalline.children('[class=volume-point]');
    var $volcurline=$voltotalline.children('[class=volume-current-line]');
    var play=null;
    $endtime.text(secToMinx(endsec));
    $pauseplay.click(function(){
        isPlay=!isPlay;
        if (isPlay) {
            $faplay.removeClass('fa-play').addClass('fa-pause');
            audio.play();
            play=setInterval(function(){
                var curtime=audio.currentTime;
                $starttime.text(secToMinx(curtime));
                var percentage=curtime/endsec;
                var pointleft=percentage*$totalline.width();
                var curlinewidth=pointleft;
                if (!audio.ended) {
                    $playpoint.css("left",pointleft-2+'px');
                    $curline.css("width",curlinewidth+'px');
                    // console.log("play");
                }else{
                    clearInterval(play);
                    audio.current=0;
                    isPlay=false;
                    $faplay.removeClass('fa-pause').addClass('fa-play');
                }
            },1000)
        }
        else{
            $faplay.removeClass('fa-pause').addClass('fa-play');
            audio.pause();
            clearInterval(play);
        }
    });
    $totalline.click(function(e){
        var totalwith=$totalline.width();
        var left=e.pageX-$totalline.offset().left;
        left=left<0?0:left;
        left=left>totalwith?totalwith:left;
        audio.currentTime=(left/totalwith)*endsec;
        isPlay=false;
        $pauseplay.click();
        // console.log("play");
    });
    var isDown=false;
    $playpoint.mousedown(function(e){
        isDown=true;
    });
    var isVolDown=false;
    $voltotalline.click(function(e){
        setVol(e.pageX);
    });
    $volpoint.mousedown(function(){
        isVolDown=true;
    });
    $(".player1 .volume-icon img").click(function(e){
        setVol(e.pageX);
    });



    //显示时长
    var length=$(".users-voice").length;
    for(var i=0;i<length;i++){
        var time=$(".play-record audio")[i].duration;
        time=parseInt(time);
        $(".record-sec").eq(i).text('');
    }


    if ($(".player2")[0]) {
        var $pauseplay2=$(".player2 .pause-play");
        var audio2=document.getElementById("audio2");
        var endsec2=audio2.duration;
        var isPlay2=false;
        var $starttime2=$(".player2 .start-time");
        var $endtime2=$(".player2 .end-time");
        var $totalline2=$(".player2 .play-line");
        var $curline2=$(".player2 .play-current-line");
        var $playpoint2=$(".player2 .play-point");
        var $faplay2=$pauseplay2.find('i');
        var $voltotalline2=$(".player2 .volume-line");
        var volleft2=$voltotalline2.offset().left;
        var volwidth2=$voltotalline2.width();
        var $volpoint2=$voltotalline2.children('[class=volume-point]');
        var $volcurline2=$voltotalline2.children('[class=volume-current-line]');
        var play2=null;
        $endtime2.text(secToMinx(endsec2));
        $pauseplay2.click(function(){
            isPlay2=!isPlay2;
            if (isPlay2) {
                $faplay2.removeClass('fa-play').addClass('fa-pause');
                audio2.play();
                play2=setInterval(function(){
                    var curtime2=audio2.currentTime;
                    $starttime2.text(secToMinx(curtime2));
                    var percentage2=curtime2/endsec2;
                    var pointleft2=percentage2*$totalline2.width();
                    var curlinewidth2=pointleft2;
                    if (!audio2.ended) {
                        $playpoint2.css("left",pointleft2-2+'px');
                        $curline2.css("width",curlinewidth2+'px');
                        // console.log("play");
                    }else{
                        clearInterval(play2);
                        audio2.current=0;
                        isPlay2=false;
                        $faplay2.removeClass('fa-pause').addClass('fa-play');
                    }
                },1000)
            }
            else{
                $faplay2.removeClass('fa-pause').addClass('fa-play');
                audio2.pause();
                clearInterval(play2);
            }
        });
        $totalline2.click(function(e){
            var totalwith2=$totalline2.width();
            var left2=e.pageX-$totalline2.offset().left;
            left2=left2<0?0:left2;
            left2=left2>totalwith2?totalwith2:left2;
            audio2.currentTime=(left2/totalwith2)*endsec2;
            isPlay2=false;
            $pauseplay2.click();
        });
        var isDown2=false;
        $playpoint2.mousedown(function(e){
            isDown2=true;
        });
       
        var isVolDown2=false;
        $voltotalline2.click(function(e){
            setVol2(e.pageX);
        });
        $volpoint2.mousedown(function(){
            isVolDown2=true;
        });
        $(".player2 .volume-icon img").click(function(e){
            setVol2(e.pageX);
        });

    }
    $(window).mouseup(function(e){
        if (isDown2) {
            isDown2=false;
            isPlay2=false;
            $pauseplay2.click();
        }
        if (isVolDown2) {
            isVolDown2=false;
            setVol2(e.pageX);
        }
        if (isDown) {
            isDown=false;
            isPlay=false;
            $pauseplay.click();
        }
        if (isVolDown) {
            isVolDown=false;
            setVol(e.pageX);
        }
    });
    $(window).mousemove(function(e){
        if (isDown2) {
            var totalwith2=$totalline2.width();
            var left2=e.pageX-$totalline2.offset().left;
            left2=left2<0?0:left2;
            left2=left2>totalwith2?totalwith2:left;
            $playpoint2.css("left",left2-2+'px');
            $curline2.css("width",left2+'px');
            audio2.currentTime=(left2/totalwith2)*endsec2;
        }
        if (isVolDown2) {
            setVol2(e.pageX);
        }
        if (isDown) {
            var totalwith=$totalline.width();
            var left=e.pageX-$totalline.offset().left;
            left=left<0?0:left;
            left=left>totalwith?totalwith:left;
            $playpoint.css("left",left-2+'px');
            $curline.css("width",left+'px');
            audio.currentTime=(left/totalwith)*endsec;
        }
        if (isVolDown) {
            setVol(e.pageX);
        }
    });


    
function setVol(event){
    var voltotal=$voltotalline.width();
    event=event<volleft?volleft:event;
    event=event>(volleft+volwidth)?(volleft+volwidth):event;
    var volume=(event-volleft)/volwidth;
    $volpoint.css("left",volume*volwidth-5  +'px');
    $volcurline.width(event-volleft);
    volume=volume.toFixed(2);
    volume=parseFloat(volume);
    audio.volume=volume;
}  
function setVol2(event){
    var voltotal2=$voltotalline2.width();
    event=event<volleft2?volleft2:event;
    event=event>(volleft2+volwidth2)?(volleft2+volwidth2):event;
    var volume2=(event-volleft2)/volwidth2;
    $volpoint2.css("left",volume2*volwidth2-5  +'px');
    $volcurline2.width(event-volleft2);
    volume2=volume2.toFixed(2);
    volume2=parseFloat(volume2);
    audio2.volume=volume2;
}

});